﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Objects;
using System.Linq;
using VO.Entities;

namespace VO.Business.Controllers
{
    public static class UsersBadgesController
    {
        public static List<UserBadge> GetUsersBadges()
        {
            using (ModelVOContainer ctx = new ModelVOContainer())
            {
                return ctx.UserBadges.ToList();
            }
        }

        public static UserBadge GetUserBadge(int id)
        {
            using (ModelVOContainer ctx = new ModelVOContainer())
            {
                return ctx.UserBadges.SingleOrDefault(p => p.Id == id);
            }
        }

        public static List<UserBadge> GetUserBadgesByUserId(int userid)
        {
            using (ModelVOContainer ctx = new ModelVOContainer())
            {
                return ctx.UserBadges.Where(p => p.UserId == userid).ToList();
            }
        }

        public static bool SaveUserBadge(UserBadge userbadge, bool isnew)
        {
            using (ModelVOContainer ctx = new ModelVOContainer())
            {
                try
                {
                    ctx.UserBadges.Attach(userbadge);
                    ctx.ObjectStateManager.ChangeObjectState(userbadge, isnew ? EntityState.Added : EntityState.Modified);

                    return ctx.SaveChanges() > 0;
                }
                catch (OptimisticConcurrencyException exOpt)
                {
                    ctx.Refresh(RefreshMode.ClientWins, userbadge);

                    return ctx.SaveChanges() > 0;
                }
                catch (Exception)
                {
                    throw;
                }
            }
        }
    }
}
